package com.example.filesplit.demos.web;

import com.example.filesplit.demos.entity.HeaderResp;
import com.example.filesplit.demos.entity.TableDataResp;
import com.example.filesplit.demos.entity.TableDataResponse;
import org.apache.poi.xwpf.usermodel.*;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STMerge;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STVerticalJc;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

@RestController
@RequestMapping("/api")
public class WordSplitController {
    @PostMapping("/header")
    public List<HeaderResp> getHeader(@RequestParam("file") MultipartFile file){
        List<HeaderResp> headerResps = new ArrayList<>();
        try {
            XWPFDocument document = new XWPFDocument(file.getInputStream());
            List<XWPFTable> tables = document.getTables();
            for (XWPFTable table : tables) {
                XWPFTableRow headerRow = table.getRow(0);
                for (int j = 0; j < headerRow.getTableCells().size(); j++) {
                    HeaderResp headerResp = new HeaderResp(j, headerRow.getCell(j).getText());
                    headerResps.add(headerResp);
                }
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        return headerResps;
    }
    @PostMapping("/upload")
    public ResponseEntity<byte[]> uploadWordFile(@RequestParam("file") MultipartFile file,
                                                 @RequestParam("columnIndex") int columnIndex,
                                                 @RequestParam("synonymsFile")MultipartFile synonymsFile) {
        try {
            // 处理上传的 Word 文件
            List<String> mainUnits = extractMainUnits(file, columnIndex);
            List<String> synonyms = readSynonyms(synonymsFile);
            List<String> units = removeUnit(mainUnits, synonyms);
            List<List<String>> lists = file1(file, columnIndex);
            // 生成空 Word 文件并打包成 ZIP
            //byte[] zipData = createZipWithEmptyFiles(mainUnits, file);
            //byte[] zipData = createZipWithEmptyFiles(mainUnits, lists,file,columnIndex);
            byte[] zipData = createZipWithEmptyFiles(units, lists,file,columnIndex,synonymsFile);
            return ResponseEntity.ok()
                    .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=units.zip")
                    .body(zipData);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
        }
    }
    public List<String> removeUnit(List<String> mainUnits,List<String> synonyms){
        List<String> filteredUnits = new ArrayList<>(mainUnits);
        for (String synonym : synonyms) {
            // 移除包含在同义词中的单位
            filteredUnits.removeIf(unit -> unit.equals(synonym));
        }
        return filteredUnits;
    }
    private List<String> extractMainUnits(MultipartFile file, int columnIndex) throws IOException {
        Set<String> mainUnitSet = new HashSet<>();
        try (XWPFDocument document = new XWPFDocument(file.getInputStream())) {
            XWPFTable table = document.getTableArray(0); // 假设只处理第一个表格
            if (table != null) {
                for (int i = 1; i < table.getRows().size(); i++) { // 从1开始跳过表头
                    XWPFTableRow row = table.getRow(i);
                    if (row.getTableCells().size() > columnIndex) {
                        String cellText = row.getCell(columnIndex).getText();
                        //String[] units = cellText.split("(?<=[\\u4e00-\\u9fa5])\\s*[，,、;；]\\s*(?=[\\u4e00-\\u9fa5])");
                        String[] units = cellText.split("[，,、;；]+");
                        for (String unit : units) {
                            // 去除空格
                            unit = unit.trim();
                            // 去掉包含 "等" 的部分
                            if (unit.contains("等")) {
                                unit = unit.substring(0, unit.indexOf("等")).trim();
                            }
                            // 如果单位不为空，则添加到集合中
                            if (!unit.isEmpty()) {
                                mainUnitSet.add(unit);
                            }
                        }
                        //Collections.addAll(mainUnitSet, units);
                    }
                }
            }
        }
        return new ArrayList<>(mainUnitSet);
    }
    //直接生成表格文件
    //private byte[] createZipWithEmptyFiles(List<String> mainUnits, List<List<String>> tableData, MultipartFile file,Integer columnIndex) throws IOException {
    //    Path tempDir = Files.createTempDirectory("temp");
    //    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    //    try (ZipOutputStream zipOut = new ZipOutputStream(byteArrayOutputStream)) {
    //        // 读取表头
    //        List<String> headers = getHeaders(file);
    //        for (String unit : mainUnits) {
    //            String fileName = unit.trim() + ".docx";
    //            Path filePath = tempDir.resolve(fileName);
    //            createEmptyWordFile(headers, filePath); // 创建空的 Word 文件
    //
    //            // 将符合条件的行数据添加到 Word 文件中
    //            try (XWPFDocument newDoc = new XWPFDocument(new FileInputStream(filePath.toFile()))) {
    //                XWPFTable newTable = newDoc.getTableArray(0); // 获取创建的表格
    //                int rowCount = newTable.getRows().size();
    //
    //                for (List<String> row : tableData) {
    //                    // 检查指定列是否包含单位
    //                    String unitInColumn = row.get(columnIndex); // 假设 columnIndex 是传入的参数
    //                    if (unitInColumn.contains(unit)) {
    //                        // 创建新行并添加到表格中
    //                        XWPFTableRow newRow = newTable.createRow();
    //                        for (int i = 0; i < row.size(); i++) {
    //                            newRow.getCell(i).setText(row.get(i)); // 设置行数据
    //                        }
    //                    }
    //                }
    //                newDoc.write(new FileOutputStream(filePath.toFile())); // 保存修改后的文件
    //            }
    //
    //            // 将文件添加到 ZIP
    //            zipOut.putNextEntry(new ZipEntry(fileName));
    //            try (FileInputStream fis = new FileInputStream(filePath.toFile())) {
    //                byte[] buffer = new byte[1024];
    //                int length;
    //                while ((length = fis.read(buffer)) >= 0) {
    //                    zipOut.write(buffer, 0, length);
    //                }
    //            }
    //            zipOut.closeEntry();
    //        }
    //        zipOut.finish();
    //    } finally {
    //        // 清理临时文件
    //        Files.walk(tempDir)
    //                .sorted(Comparator.reverseOrder())
    //                .map(Path::toFile)
    //                .forEach(File::delete);
    //    }
    //    return byteArrayOutputStream.toByteArray();
    //}
    //保留原有文件
    private byte[] createZipWithEmptyFiles(List<String> mainUnits, List<List<String>> tableData, MultipartFile file, Integer columnIndex) throws IOException {
        Path tempDir = Files.createTempDirectory("temp");
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        try (ZipOutputStream zipOut = new ZipOutputStream(byteArrayOutputStream)) {
            for (String unit : mainUnits) {
                String fileName = unit.trim() + ".docx";
                Path filePath = tempDir.resolve(fileName);
                createEmptyWordFile(file, filePath); // 创建空的 Word 文件并保留内容

                // 将符合条件的行数据添加到 Word 文件中
                try (XWPFDocument newDoc = new XWPFDocument(new FileInputStream(filePath.toFile()))) {
                    XWPFTable newTable = newDoc.getTableArray(0); // 获取创建的表格

                    for (List<String> row : tableData) {
                        // 检查指定列是否包含单位
                        String unitInColumn = row.get(columnIndex);
                        if (unitInColumn.contains(unit)) {
                            // 创建新行并添加到表格中
                            XWPFTableRow newRow = newTable.createRow();
                            for (int i = 0; i < row.size(); i++) {
                                newRow.getCell(i).setText(row.get(i)); // 设置行数据
                            }
                        }
                    }
                    newDoc.write(new FileOutputStream(filePath.toFile())); // 保存修改后的文件
                }

                // 将文件添加到 ZIP
                zipOut.putNextEntry(new ZipEntry(fileName));
                try (FileInputStream fis = new FileInputStream(filePath.toFile())) {
                    byte[] buffer = new byte[1024];
                    int length;
                    while ((length = fis.read(buffer)) >= 0) {
                        zipOut.write(buffer, 0, length);
                    }
                }
                zipOut.closeEntry();
            }
            zipOut.finish();
        } finally {
            // 清理临时文件
            Files.walk(tempDir)
                    .sorted(Comparator.reverseOrder())
                    .map(Path::toFile)
                    .forEach(File::delete);
        }
        return byteArrayOutputStream.toByteArray();
    }
    //加上同义词文件
    //public byte[] createZipWithEmptyFiles(List<String> mainUnits, List<List<String>> tableData, MultipartFile file, Integer columnIndex, MultipartFile synonymsFile) throws IOException {
    //    Path tempDir = Files.createTempDirectory("temp");
    //    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    //    try (ZipOutputStream zipOut = new ZipOutputStream(byteArrayOutputStream)) {
    //        // 读取表头
    //        // 读取同义词文件内容
    //       Map<String,String[]> synonymsList1 = readSynonyms1(synonymsFile);
    //        for (String unit : mainUnits) {
    //            String fileName = unit.trim() + ".docx";
    //            Path filePath = tempDir.resolve(fileName);
    //            createEmptyWordFile(file, filePath);
    //
    //            // 将符合条件的行数据添加到 Word 文件中
    //            try (XWPFDocument newDoc = new XWPFDocument(new FileInputStream(filePath.toFile()))) {
    //                XWPFTable newTable = newDoc.getTableArray(0);
    //                int rowCount = newTable.getRows().size();
    //
    //                for (List<String> row : tableData) {
    //                    String unitInColumn = row.get(columnIndex);
    //                    //if (unitInColumn.contains(unit) || handleSynonyms(unitInColumn, unit, synonymsList)) {
    //                    if (unitInColumn.contains(unit) || handleSynonyms1(unitInColumn, unit, synonymsList1)) {
    //                        XWPFTableRow newRow = newTable.createRow();
    //                        for (int i = 0; i < row.size(); i++) {
    //                            newRow.getCell(i).setText(row.get(i));
    //                        }
    //                    }
    //                }
    //                newDoc.write(new FileOutputStream(filePath.toFile()));
    //            }
    //
    //            // 将文件添加到 ZIP
    //            zipOut.putNextEntry(new ZipEntry(fileName));
    //            try (FileInputStream fis = new FileInputStream(filePath.toFile())) {
    //                byte[] buffer = new byte[1024];
    //                int length;
    //                while ((length = fis.read(buffer)) >= 0) {
    //                    zipOut.write(buffer, 0, length);
    //                }
    //            }
    //            zipOut.closeEntry();
    //        }
    //        zipOut.finish();
    //    } finally {
    //        // 清理临时文件
    //        Files.walk(tempDir)
    //                .sorted(Comparator.reverseOrder())
    //                .map(Path::toFile)
    //                .forEach(File::delete);
    //    }
    //    return byteArrayOutputStream.toByteArray();
    //}

    public byte[] createZipWithEmptyFiles(List<String> mainUnits, List<List<String>> tableData, MultipartFile file, Integer columnIndex, MultipartFile synonymsFile) throws IOException {
        Path tempDir = Files.createTempDirectory("temp");
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        try (ZipOutputStream zipOut = new ZipOutputStream(byteArrayOutputStream)) {
            // 读取同义词文件内容
            Map<String, String[]> synonymsList1 = readSynonyms1(synonymsFile);
            for (String unit : mainUnits) {
                String fileName = unit.trim() + ".docx";
                Path filePath = tempDir.resolve(fileName);
                createEmptyWordFile(file, filePath);

                // 将符合条件的行数据添加到 Word 文件中
                try (XWPFDocument newDoc = new XWPFDocument(new FileInputStream(filePath.toFile()))) {
                    XWPFTable newTable = newDoc.getTableArray(0);

                    // 添加数据到表格
                    for (List<String> row : tableData) {
                        String unitInColumn = row.get(columnIndex);
                        if (unitInColumn.contains(unit) || handleSynonyms1(unitInColumn, unit, synonymsList1)) {
                            XWPFTableRow newRow = newTable.createRow();
                            for (int i = 0; i < row.size(); i++) {
                                newRow.getCell(i).setText(row.get(i));
                            }
                        }
                    }
                    mergeSameContentCells(newTable);
                    // 合并相同内容的单元格

                    newDoc.write(new FileOutputStream(filePath.toFile()));
                }

                // 将文件添加到 ZIP
                zipOut.putNextEntry(new ZipEntry(fileName));
                try (FileInputStream fis = new FileInputStream(filePath.toFile())) {
                    byte[] buffer = new byte[1024];
                    int length;
                    while ((length = fis.read(buffer)) >= 0) {
                        zipOut.write(buffer, 0, length);
                    }
                }
                zipOut.closeEntry();
            }
            zipOut.finish();
        } finally {
            // 清理临时文件
            Files.walk(tempDir)
                    .sorted(Comparator.reverseOrder())
                    .map(Path::toFile)
                    .forEach(File::delete);
        }
        return byteArrayOutputStream.toByteArray();
    }

    private void mergeSameContentCells(XWPFTable table) {
        int rowCount = table.getRows().size();//行数
        int columnCount = table.getRow(0).getTableCells().size();//列数

        for (int columnIndex = 0; columnIndex < columnCount; columnIndex++) {
            String lastMergedValue = null;// 上一个合并的单元格值
            int lastMergedRowIndex = -1; // 上一个合并的单元格行索引
            int mergeCount = 1; // 记录合并的单元格次数

            for (int row = 1; row < rowCount; row++) {
                XWPFTableRow currentRow = table.getRow(row);
                String currentValue = currentRow.getCell(columnIndex).getText();

                if (currentValue.equals(lastMergedValue) && !currentValue.isEmpty()) {
                    mergeCount++;
                    currentRow.getCell(columnIndex).setText(""); // 清空当前单元格内容
                } else {
                    if (mergeCount > 1) {
                        mergeCells(table, lastMergedRowIndex, row, columnIndex, mergeCount);
                    }
                    lastMergedValue = currentValue;
                    lastMergedRowIndex = row;
                    mergeCount = 1;
                }
            }
            // 处理最后一组合并
            if (mergeCount > 1) {
                mergeCells(table, lastMergedRowIndex, rowCount, columnIndex, mergeCount);
            }
        }
    }

    private void mergeCells(XWPFTable table, int startRow, int endRow, int columnIndex, int mergeCount) {
        XWPFTableCell cellToMerge = table.getRow(startRow).getCell(columnIndex);
        cellToMerge.getCTTc().addNewTcPr().addNewVMerge().setVal(STMerge.RESTART); // 设置为合并的开始
        for (int row = startRow + 1; row < startRow + mergeCount; row++) {
            XWPFTableCell cell = table.getRow(row).getCell(columnIndex);
            cell.getCTTc().addNewTcPr().addNewVMerge().setVal(STMerge.CONTINUE); // 设置为合并的继续
            cell.setText(""); // 清空合并的单元格内容
        }
    }
    private boolean handleSynonyms1(String unitInColumn, String unit, Map<String,String[]> synonymsMap) {
        if (synonymsMap.containsKey(unit)){
            String[] synonyms = synonymsMap.get(unit);
            for (String synonym : synonyms) {
                if (unitInColumn.contains(synonym)){
                    return true;
                }
            }
        }
        return false;
    }

    //private boolean handleSynonyms(String unitInColumn, String unit, List<String[]> synonymsList) {
    //    for (String[] synonyms : synonymsList) {
    //        // 检查 unitInColumn 是否包含同义词组中的任意一个词
    //        boolean containsUnit = Arrays.asList(synonyms).contains(unit);
    //        for (String synonym : synonyms) {
    //            if (unitInColumn.contains(synonym) && containsUnit) {
    //                return true;
    //            }
    //        }
    //    }
    //    return false;
    //}
    //public List<String> handleDepart(List<String> mainUnits, Map<String,String[]> synonymsList1){
    //    for (Iterator<String> iterator = mainUnits.iterator(); iterator.hasNext(); ) {
    //        String unit = iterator.next();
    //        for (String[] value : synonymsList1.values()) {
    //            for (String synonym : value) {
    //                if (unit.equals(synonym)) {
    //                    iterator.remove(); // 移除包含在 synonymsList1 的值的单位
    //                    break; // 找到匹配后跳出内层循环
    //                }
    //            }
    //        }
    //    }
    //    return mainUnits;
    //}
    //@PostMapping("/readSynonyms")
    public List<String> readSynonyms(@RequestParam("file") MultipartFile synonymsFile) throws IOException {
        Set<String> uniqueResults = new HashSet<>();
        try (InputStreamReader irs = new InputStreamReader(synonymsFile.getInputStream(),StandardCharsets.UTF_8)) {
            // 假设同义词文件是每行一个同义词组，用 分隔
            java.util.Scanner scanner = new java.util.Scanner(irs);
            while (scanner.hasNextLine()) {
                String line = scanner.nextLine();
                String[] synonyms = line.split(" ");
                for(int i=1;i<synonyms.length;i++){
                    uniqueResults.add(synonyms[i]);
                }
            }
        }
        return new ArrayList<>(uniqueResults);
    }
    public Map<String,String[]> readSynonyms1(@RequestParam("file")MultipartFile synonymsFile) throws IOException {
        Map<String, String[]> synonymsMap = new HashMap<>();
        try(InputStreamReader irs = new InputStreamReader(synonymsFile.getInputStream(), StandardCharsets.UTF_8)){
            Scanner scanner = new Scanner(irs);
            while (scanner.hasNextLine()){
                String line = scanner.nextLine();
                String[]  synonyms = line.split(" ");
                if (synonyms.length>0){
                    String key=synonyms[0];
                    String[] values = Arrays.copyOfRange(synonyms, 1, synonyms.length);
                    synonymsMap.put(key,values);
                }
            }
        }
        return synonymsMap;
    }
    //@PostMapping("/readSynonyms")
    //public ResponseEntity<List<String[]>> readSynonyms(@RequestParam("file") MultipartFile synonymsFile) throws IOException {
    //    List<String[]> synonymsList = new ArrayList<>();
    //    try (InputStreamReader isr = new InputStreamReader(synonymsFile.getInputStream(), StandardCharsets.UTF_8)) {
    //        java.util.Scanner scanner = new java.util.Scanner(isr);
    //        while (scanner.hasNextLine()) {
    //            String line = scanner.nextLine();
    //            String[] synonyms = line.split(" ");
    //            synonymsList.add(synonyms);
    //        }
    //    }
    //    return ResponseEntity.ok()
    //            .contentType(new MediaType("application", "json", StandardCharsets.UTF_8))
    //            .body(synonymsList);
    //}

    private List<String> getHeaders(MultipartFile file) throws IOException {
        List<String> headers = new ArrayList<>();
        try (XWPFDocument document = new XWPFDocument(file.getInputStream())) {
            XWPFTable table = document.getTableArray(0); // 假设只处理第一个表格
            if (table != null) {
                XWPFTableRow headerRow = table.getRow(0);
                for (int i = 0; i < headerRow.getTableCells().size(); i++) {
                    headers.add(headerRow.getCell(i).getText());
                }
            }
        }
        return headers;
    }

    private void createEmptyWordFile1(List<String> headers, Path filePath) throws IOException {
        try (XWPFDocument newDoc = new XWPFDocument()) {
            XWPFTable newTable = newDoc.createTable(1, headers.size());//需要修改
            XWPFTableRow newRow = newTable.getRow(0);
            for (int i = 0; i < headers.size(); i++) {
                newRow.getCell(i).setText(headers.get(i)); // 设置表头
            }
            newDoc.write(new FileOutputStream(filePath.toFile()));
        }
    }
    private void createEmptyWordFile(MultipartFile file, Path filePath) throws IOException {
        try (XWPFDocument originalDoc = new XWPFDocument(file.getInputStream())) {
            // 获取原始文档中的表格
            XWPFTable originalTable = originalDoc.getTableArray(0); // 假设只处理第一个表格
            if (originalTable != null) {
                // 清空原表格的所有行，保留表头
                for (int i = originalTable.getRows().size() - 1; i > 0; i--) {
                    originalTable.removeRow(i);
                }
            }

            // 将修改后的文档写入文件
            try (FileOutputStream out = new FileOutputStream(filePath.toFile())) {
                originalDoc.write(out);
            }
        }
    }

    //private byte[] createZipWithEmptyFiles(List<String> mainUnits, List<List<String>> tableData, MultipartFile file, Integer columnIndex) throws IOException {
    //    Path tempDir = Files.createTempDirectory("temp");
    //    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    //    try (ZipOutputStream zipOut = new ZipOutputStream(byteArrayOutputStream)) {
    //        // 读取表头
    //        List<String> headers;
    //        try (XWPFDocument document = new XWPFDocument(file.getInputStream())) {
    //            XWPFTable table = document.getTableArray(0); // 假设只处理第一个表格
    //            if (table != null) {
    //                XWPFTableRow headerRow = table.getRow(0);
    //                headers = headerRow.getTableCells().stream()
    //                        .map(XWPFTableCell::getText)
    //                        .collect(Collectors.toList());
    //            } else {
    //                headers = Collections.emptyList(); // 如果没有表格，返回空列表
    //            }
    //        }
    //
    //        for (String unit : mainUnits) {
    //            String fileName = unit.trim() + ".docx";
    //            Path filePath = tempDir.resolve(fileName);
    //
    //            // 创建空的 Word 文件并设置表头
    //            try (XWPFDocument newDoc = new XWPFDocument()) {
    //                XWPFTable newTable = newDoc.createTable(1, headers.size());
    //                XWPFTableRow newRow = newTable.getRow(0);
    //                IntStream.range(0, headers.size()).forEach(i -> newRow.getCell(i).setText(headers.get(i))); // 设置表头
    //
    //                // 将符合条件的行数据添加到 Word 文件中
    //                for (List<String> row : tableData) {
    //                    String unitInColumn = row.get(columnIndex);
    //                    if (unitInColumn.contains(unit)) {
    //                        XWPFTableRow newDataRow = newTable.createRow();
    //                        IntStream.range(0, row.size()).forEach(i -> newDataRow.getCell(i).setText(row.get(i))); // 设置行数据
    //                    }
    //                }
    //                newDoc.write(new FileOutputStream(filePath.toFile())); // 保存修改后的文件
    //            }
    //
    //            // 将文件添加到 ZIP
    //            zipOut.putNextEntry(new ZipEntry(fileName));
    //            try (FileInputStream fis = new FileInputStream(filePath.toFile())) {
    //                byte[] buffer = new byte[1024];
    //                int length;
    //                while ((length = fis.read(buffer)) >= 0) {
    //                    zipOut.write(buffer, 0, length);
    //                }
    //            }
    //            zipOut.closeEntry();
    //        }
    //        zipOut.finish();
    //    } finally {
    //        // 清理临时文件
    //        Files.walk(tempDir)
    //                .sorted(Comparator.reverseOrder())
    //                .map(Path::toFile)
    //                .forEach(File::delete);
    //    }
    //    return byteArrayOutputStream.toByteArray();
    //}
    //private byte[] createZipWithEmptyFiles(List<String> mainUnits, MultipartFile file) throws IOException {
    //    Path tempDir = Files.createTempDirectory("temp");
    //    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    //    try (ZipOutputStream zipOut = new ZipOutputStream(byteArrayOutputStream)) {
    //        // 读取表头
    //        List<String> headers = getHeaders(file);
    //        for (String unit : mainUnits) {
    //            String fileName = unit.trim() + ".docx";
    //            createEmptyWordFile(headers, tempDir.resolve(fileName));
    //            zipOut.putNextEntry(new ZipEntry(fileName));
    //            try (FileInputStream fis = new FileInputStream(tempDir.resolve(fileName).toFile())) {
    //                byte[] buffer = new byte[1024];
    //                int length;
    //                while ((length = fis.read(buffer)) >= 0) {
    //                    zipOut.write(buffer, 0, length);
    //                }
    //            }
    //            zipOut.closeEntry();
    //        }
    //        zipOut.finish();
    //    } finally {
    //        // 清理临时文件
    //        Files.walk(tempDir)
    //                .sorted(Comparator.reverseOrder())
    //                .map(Path::toFile)
    //                .forEach(File::delete);
    //    }
    //    return byteArrayOutputStream.toByteArray();
    //}





    @PostMapping("/file1")
    public List<List<String>> file1(@RequestParam("file") MultipartFile file,
                                    @RequestParam("columnIndex") int columnIndex) throws IOException {
        List<List<String>> tableData = new ArrayList<>();
        // 读取 Word 文件
        try (XWPFDocument document = new XWPFDocument(file.getInputStream())) {
            // 假设只处理第一个表格
            XWPFTable table = document.getTables().get(0);
            int rowCount = table.getRows().size();
            int columnCount = table.getRow(0).getTableCells().size();

            // 用于跟踪已处理的单元格
            String[][] mergedCellValues = new String[rowCount][columnCount];
            for (int i = 1; i < rowCount; i++) {
                List<String> rowData = new ArrayList<>();
                XWPFTableRow row = table.getRow(i);
                if (row.getTableCells().size()<columnCount){
                    continue;
                }
                for (int j = 0; j < columnCount; j++) {
                    XWPFTableCell cell = table.getRow(i).getCell(j);
                    String cellText = cell.getText();
                    // 检查当前单元格是否是合并单元格
                    if (cellText.isEmpty()||"".equals(cellText)){
                        mergedCellValues[i][j]=mergedCellValues[i-1][j];
                    }else {
                        // 普通单元格，直接使用内容
                        mergedCellValues[i][j] = cellText;
                    }
                    // 添加到行数据
                    rowData.add(mergedCellValues[i][j]);
                }
                tableData.add(rowData);
            }
        }
        return tableData;
    }

    @PostMapping("/")
    public void getDepart(@RequestParam("file") MultipartFile file,
                          @RequestParam("columnIndex") int columnIndex)throws IOException{

    }

    //@PostMapping("/read")
    //public void readTable(@RequestParam("file") MultipartFile file){
    //    try (XWPFDocument document = new XWPFDocument(file.getInputStream())) {
    //        for (XWPFTable table : document.getTables()) {
    //            // 读取表头
    //            // 存储合并单元格的内容
    //            // 遍历表格行
    //            for (int i = 0; i < table.getNumberOfRows(); i++) {
    //                XWPFTableRow row = table.getRow(i);
    //                for (int j = 0; j < row.getTableCells().size(); j++) {
    //                    XWPFTableCell cell = row.getCell(j);
    //                    String text = cell.getText();
    //                }
    //            }
    //        }
    //    }catch (IOException e) {
    //        throw new RuntimeException("报错："+e);
    //    }
    //}
    //
    //@PostMapping("/copy")
    //public ResponseEntity<byte[]> uploadWordFile(@RequestParam("file") MultipartFile file) {
    //    if (file.isEmpty()) {
    //        return ResponseEntity.badRequest().body(null);
    //    }
    //
    //    try (XWPFDocument sourceDoc = new XWPFDocument(file.getInputStream());
    //         XWPFDocument targetDoc = new XWPFDocument();
    //         ByteArrayOutputStream out = new ByteArrayOutputStream()) {
    //
    //        // 复制表格
    //        for (XWPFTable table : sourceDoc.getTables()) {
    //            XWPFTable newTable = targetDoc.createTable();
    //            copyTable(table, newTable);
    //        }
    //
    //        // 将新的 Word 文件写入输出流
    //        targetDoc.write(out);
    //        byte[] bytes = out.toByteArray();
    //
    //        // 设置响应头
    //        HttpHeaders headers = new HttpHeaders();
    //        headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=copied_table.docx");
    //        headers.add(HttpHeaders.CONTENT_TYPE, "application/vnd.openxmlformats-officedocument.wordprocessingml.document");
    //
    //        return new ResponseEntity<>(bytes, headers, HttpStatus.OK);
    //    } catch (IOException e) {
    //        e.printStackTrace();
    //        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
    //    }
    //}
    //
    //private void copyTable(XWPFTable sourceTable, XWPFTable targetTable) {
    //    // 复制行
    //    for (int i = 0; i < sourceTable.getNumberOfRows(); i++) {
    //        XWPFTableRow sourceRow = sourceTable.getRow(i);
    //        XWPFTableRow targetRow = targetTable.createRow();
    //
    //        // 复制单元格
    //        for (int j = 0; j < sourceRow.getTableCells().size(); j++) {
    //            XWPFTableCell sourceCell = sourceRow.getCell(j);
    //            if (sourceCell != null) {
    //                // 创建目标单元格
    //                XWPFTableCell targetCell = targetRow.createCell();
    //                String cellText = sourceCell.getText();
    //                targetCell.setText(cellText);
    //            }
    //        }
    //    }
    //}
    //
    //@PostMapping("/fileContext1")
    //public TableDataResponse getTableData1(@RequestParam("file") MultipartFile file) throws IOException {
    //    List<List<String>> fileData = new ArrayList<>();
    //    XWPFDocument document = new XWPFDocument(file.getInputStream());
    //    XWPFTable table = document.getTables().get(0); // 只考虑第一个表格
    //    List<XWPFTableRow> rows = new ArrayList<>();
    //
    //    // 遍历表格的所有行
    //    for (int j = 0; j < table.getRows().size(); j++) {
    //        XWPFTableRow row = table.getRow(j);
    //        List<String> rowData = new ArrayList<>();
    //
    //        // 读取当前行的所有单元格内容
    //        for (int index = 0; index < row.getTableCells().size(); index++) {
    //            rowData.add(row.getCell(index).getText()); // 添加单元格内容
    //        }
    //
    //        fileData.add(rowData); // 添加行数据
    //        rows.add(row); // 添加行对象
    //    }
    //
    //    return new TableDataResponse(document, table, rows, fileData); // 返回文档、表格、行数据和单元格数据
    //}
    //@PostMapping("/mergeCell")
    //public List<List<String>> mergeCell(@RequestParam("file") MultipartFile file) throws IOException {
    //    List<List<String>> tableData = new ArrayList<>();
    //
    //    // 读取 Word 文件
    //    try (XWPFDocument document = new XWPFDocument(file.getInputStream())) {
    //        // 假设只处理第一个表格
    //        XWPFTable table = document.getTables().get(0);
    //        int rowCount = table.getRows().size();
    //
    //        // 用于跟踪已处理的单元格
    //        boolean[][] mergedCells = new boolean[rowCount][table.getRow(0).getTableCells().size()];
    //
    //        for (int i = 0; i < rowCount; i++) {
    //            List<String> rowData = new ArrayList<>();
    //            int cellCount = table.getRow(i).getTableCells().size();
    //
    //            for (int j = 0; j < cellCount; j++) {
    //                XWPFTableCell cell = table.getRow(i).getCell(j);
    //                // 检查当前单元格是否已经被处理
    //                if (mergedCells[i][j]) {
    //                    rowData.add(""); // 如果已经处理过，添加空字符串
    //                } else {
    //                    rowData.add(cell.getText());
    //                    // 检查是否是合并单元格
    //                    if (cell.getCTTc().getTcPr().getVMerge() != null) {
    //                        mergedCells[i][j] = true; // 标记为已处理
    //                    }
    //                }
    //            }
    //            tableData.add(rowData);
    //        }
    //    }
    //
    //    return tableData;
    //}
    //
    //@PostMapping("/fileContext")
    //public TableDataResp getTableData(@RequestParam("file") MultipartFile file) throws IOException {
    //    List<List<String>> fileData = new ArrayList<>();
    //    XWPFDocument document = new XWPFDocument(file.getInputStream());
    //    XWPFTable table = document.getTables().get(0); // 只考虑第一个表格
    //
    //    // 遍历表格的所有行
    //    for (int j = 0; j < table.getRows().size(); j++) {
    //        XWPFTableRow row = table.getRow(j);
    //        List<String> rowData = new ArrayList<>();
    //
    //        // 读取当前行的所有单元格内容
    //        for (int index = 0; index < row.getTableCells().size(); index++) {
    //            rowData.add(row.getCell(index).getText()); // 添加单元格内容
    //        }
    //
    //        fileData.add(rowData); // 添加行数据
    //    }
    //
    //    // 仅返回表格数据，不返回XWPFDocument，以避免序列化问题
    //    return new TableDataResp(table, fileData); // 返回表格和行数据
    //}



    @PostMapping("/split")
    public ResponseEntity<ByteArrayResource> splitWordFile(@RequestParam("file") MultipartFile file) throws IOException {
        List<XWPFDocument> documents = splitTable(file);
        byte[] zipFile = createZipFile(documents);

        // 设置响应头
        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=split_documents.zip");

        return ResponseEntity.ok()
                .headers(headers)
                .contentType(MediaType.APPLICATION_OCTET_STREAM)
                .body(new ByteArrayResource(zipFile));
    }

    private List<XWPFDocument> splitTable(MultipartFile file) throws IOException {
        List<XWPFDocument> documents = new ArrayList<>();

        try (XWPFDocument document = new XWPFDocument(file.getInputStream())) {
            for (XWPFTable table : document.getTables()) {
                // 读取表头
                List<String> headers = new ArrayList<>();
                XWPFTableRow headerRow = table.getRow(0);
                for (XWPFTableCell cell : headerRow.getTableCells()) {
                    headers.add(cell.getText());
                }

                // 存储合并单元格的内容
                Map<Integer, List<String>> mergedCells = new HashMap<>();

                // 遍历表格行
                for (int i = 1; i < table.getNumberOfRows(); i++) {
                    XWPFTableRow row = table.getRow(i);
                    for (int j = 0; j < row.getTableCells().size(); j++) {
                        XWPFTableCell cell = row.getCell(j);

                        // 检查合并单元格
                        if (cell.getText().isEmpty()) {
                            // 如果单元格为空，检查是否有合并内容
                            if (mergedCells.containsKey(j)) {
                                // 使用之前存储的内容
                                cell.setText(mergedCells.get(j).get(0)); // 取第一个合并内容
                            }
                        } else {
                            // 如果单元格有内容，存储内容
                            mergedCells.put(j, new ArrayList<>());
                            mergedCells.get(j).add(cell.getText());
                        }
                    }
                }

                // 处理每一行，提取主要内容和责任单位
                for (int i = 1; i < table.getNumberOfRows(); i++) { // 从第二行开始
                    XWPFTableRow row = table.getRow(i);
                    String mainContent = row.getCell(2).getText(); // 假设主要内容在第一列
                    String responsibleUnitCell = mergedCells.get(3) != null ? mergedCells.get(3).get(0) : ""; // 假设责任单位在第二列

                    // 拆分责任单位
                    String[] responsibleUnits = responsibleUnitCell.split(","); // 以逗号拆分
                    for (String responsibleUnit : responsibleUnits) {
                        XWPFDocument newDoc = new XWPFDocument();
                        XWPFTable newTable = newDoc.createTable(1, headers.size()); // 创建新表格，列数与表头相同

                        // 填充表头
                        for (int j = 0; j < headers.size(); j++) {
                            newTable.getRow(0).getCell(j).setText(headers.get(j));
                        }

                        // 填充主要内容和责任单位
                        newTable.getRow(1).getCell(0).setText(mainContent);
                        newTable.getRow(1).getCell(1).setText(responsibleUnit.trim()); // 去除多余空格
                        // 其他字段留空
                        for (int j = 2; j < headers.size(); j++) {
                            newTable.getRow(1).getCell(j).setText(""); // 其他字段留空
                        }

                        documents.add(newDoc);
                    }
                }
            }
        }

        return documents;
    }

    private byte[] createZipFile(List<XWPFDocument> documents) throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try (ZipOutputStream zos = new ZipOutputStream(baos)) {
            for (int i = 0; i < documents.size(); i++) {
                XWPFDocument doc = documents.get(i);
                File tempFile = File.createTempFile("splitDoc" + i, ".docx");
                try (FileOutputStream fos = new FileOutputStream(tempFile)) {
                    doc.write(fos);
                }
                try (FileInputStream fis = new FileInputStream(tempFile)) {
                    ZipEntry zipEntry = new ZipEntry("splitDoc" + i + ".docx");
                    zos.putNextEntry(zipEntry);
                    byte[] buffer = new byte[1024];
                    int length;
                    while ((length = fis.read(buffer)) >= 0) {
                        zos.write(buffer, 0, length);
                    }
                    zos.closeEntry();
                }
                Files.delete(tempFile.toPath()); // 删除临时文件
            }
        }
        return baos.toByteArray();
    }
}
